package com.android.accessibility.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.text.TextUtils;

public class PersistUtils {

    public static String readDecryptedStringFromFile(Context context, String fileName) {
        return readDecryptedStringFromFile(context, fileName, true);
    }

    public static String readDecryptedStringFromFile(Context context, String fileName, boolean encrypted) {
        StringBuilder builder = new StringBuilder();
        try {
            InputStream is = context.openFileInput(fileName);
            byte[] buf = new byte[1024];
            int read = 0;
            while((read = is.read(buf)) > 0) {
                builder.append(new String(buf, 0, read));
            }
            is.close();
        } catch (FileNotFoundException e) {
            Log.d(Log.TAG, "error : " + e);
        } catch (IOException e) {
            Log.d(Log.TAG, "error : " + e);
        } catch (NullPointerException e) {
            Log.d(Log.TAG, "error : " + e);
        }
        String source = builder.toString();
        if (TextUtils.isEmpty(source)) {
            return null;
        }
        String dst = null;
        if (encrypted) {
            try {
                dst = AuthHelper.decrypt(source);
            } catch(Exception e) {
            }
        } else {
            dst = source;
        }
        return dst;
    }

    public static void saveEncryptedStringToFile(String fileName, Context context, String source) {
        saveEncryptedStringToFile(fileName, context, source, true);
    }

    public static void saveEncryptedStringToFile(String fileName, Context context, String source, boolean encrypted) {
        String dst = null;
        if (encrypted) {
            try {
                dst = AuthHelper.encrypt(source);
            } catch(Exception e) {
            }
        } else {
            dst = source;
        }
        if (TextUtils.isEmpty(dst)) {
            return;
        }
        try {
            FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            fos.write(dst.getBytes());
            fos.close();
        } catch(Exception e) {
        }
    }
}
